<?php

namespace app\login\controller;

// use app\common\controller\AdminController;
// use app\common\services\annotation\ControllerAnnotation;
// use app\common\services\annotation\NodeAnnotation;

use support\Request; //请求类
use support\Response; //请求类
use think\facade\Db; //数据库类
use think\App; //初始化
use think\Exception; //异常
use app\common\traits\JumpTrait;



/**
 * @ControllerAnnotation(title="group_user")
 */
class IndexController
{
    
    use JumpTrait;
    /**
     * 不需要登录的方法
     */
    protected $noNeedLogin = ['login','reg','sendcode'];

    public function login(Request $request){
		if($request->isAjax()) {
			if($request->post('account') and $request->post('password')) {
			} else {
				return $this->error('账号或密码未输入');
			}
			$User=Db::name('user');
			$data['name']=$request->post('account');
			$data['pw']=md5($request->post('password'));
			
            function getUniqueCdk($length = 8) {
                $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $randomString = '';
            
                do {
                    $randomString = '';
                    for ($i = 0; $i < $length; $i++) {
                        $randomString .= $characters[rand(0, strlen($characters) - 1)];
                    }
                } while (DB::name('user')->where('code', $randomString)->find());
            
                return $randomString;
            }
            
		    if(sysconfig('game','gamelogin') != '0'){
		        //寻找账号是否存在
		        
		        $sqlconnect = Db::connect('d_taiwan');
		        if(!$sqlconnect){
		            return $this->error('游戏数据库连接失败,请联系管理员');
		        }
		        
                $return = $sqlconnect->table('accounts')->where(['accountname'=>$data['name'],'password'=>$data['pw']])->find();
                if($return){
                    $bendi = $User->where(['name'=>$data['name']])->find();
                    if($bendi){
                        //同步游戏密码到云库
                        if($bendi['pw'] != $data['pw']){ $User->where(['id'=>$bendi['id']])->update(['pw'=>$data['pw']]); }
                    }else{
                        //没有就创建一个
                        Db::name('user')->insert(['name'=>$data['name'],'pw'=>$data['pw'],'nickname'=>'冒险家'.rand(1000,9999),'tx'=>'/qstatic/image/headimg.jpg','ip'=>$request->getRemoteIp(),'code'=>getUniqueCdk(8)]);
                    }
                    $info=$User->where(['name'=>$data['name']])->find();
                }else{
                    return $this->error('账号或密码错误1');
                }
		    }else{
		        $info=$User->where($data)->find();
		    }
		    
			if($info) {;
				$request = request();
				$ip = $request->getRemoteIp();
				if($ip) {
					$User->where($data)->update(['ip'=>$ip]);
				}

				$session = $request->session();
                $session->put(['name' => $info['name'], 'key' => $data['pw'],'uid'=>$info['id']]);

				//这里写加群 
				$官群 =sysconfig('im','gfgroup');
				$寻找 = DB::name("group_user")->where(['groupid'=>$官群,'userid'=>$info['id']])->count();
				if($寻找 < 1) {
					DB::name("group_user")->insert(['groupid'=>$官群,'userid'=>$info['id'],'zt'=>0]);
				}
				if($session->get('redirect_url') == null){
				    $redirect_url = '/chat';
				}else{
				    $redirect_url = $session->get('redirect_url');
				}
                $session->forget('redirect_url');//删除session
				return $this->success('成功登陆',[],$redirect_url);
				exit;
			}

			return $this->error('账号或密码错误2');
			exit;
		}else{
		    //已登录就跳转
		    if(session('redirect_url') == null){
			    $redirect_url = '/chat';
			}else{
			    $redirect_url = session('redirect_url');
			}
			if(session('uid')){
			    return $this->success('您已登录',[],$redirect_url);
			}
		    return view('login/index/login');
		}
        
		
	}

    public function zh_sfcz($account){
        $sqlconnect = Db::connect('d_taiwan');
        $返回 = $sqlconnect->table('accounts')->where(['accountname'=>$account])->count();
        if($返回 > 0){
            return true;
        }else{
            return false;
        }
    }
    public function zh_reg($账号,$密码,$赠点券,$赠DB){
	    $密码 = md5($密码);
	    $sqlconnect = Db::connect('d_taiwan');
	    if(!$sqlconnect){
	        return ('游戏数据库连接失败,请联系管理员');die();
	    }
	    if($this->zh_sfcz($账号)){
	        return('账号已在游戏中存在');die();
	    }
	    if(sysconfig('game','gamelogin') == '1'){
	        //RS登录器
	        try {
	            $d_taiwan = $sqlconnect;
                $d_taiwan->startTrans();
                $uid = $d_taiwan->table('accounts')->order('UID DESC')->value('UID') + 1;
                $d_taiwan->table('accounts')->insert(['UID'=>$uid,'accountname'=>$账号,'password'=>$密码]);
                $d_taiwan->table('member_white_account')->insert(['m_id'=>$uid]);
                $d_taiwan->table('member_info')->insert(['m_id'=>$uid,'user_id'=>$uid]);
                $d_taiwan->commit();
                $taiwan_login = Db::connect('taiwan_login');
                $taiwan_login->startTrans();
                $taiwan_login->table('member_login')->insert(['m_id'=>$uid]);
                $taiwan_login->commit();
                $taiwan_billing = Db::connect('taiwan_billing');
                $taiwan_billing->startTrans();
                $taiwan_billing->table('cash_cera')->insert(['account'=>$uid,'cera'=>$赠点券,'mod_tran'=>"0"]);
                $taiwan_billing->table('cash_cera_point')->insert(['account'=>$uid,'cera_point'=>$赠DB]);
                $taiwan_billing->commit();
                $Rslogin = Db::connect('Rslogin');
                $Rslogin->startTrans();
                $Rslogin->table('accountInfo')->insert(['UID'=>$uid,'accountname'=>$账号,'password'=>$密码,'ip'=>'127.0.0.1','qq'=>'0','safepasswd'=>$账号,'machinecode'=>'9A:D8:CD:4C:0A:1F','registerTime'=>'0000-00-00 00:00:00','registerCdkey'=>'0','isBlackList'=>'0','loginTime'=>'0000-00-00 00:00:00']);
                $Rslogin->commit();
                return('ok');
	            die();
            } catch (\Exception $e) {
                // 出现异常，回滚事务
                $d_taiwan->rollback();
                $taiwan_login->rollback();
                $taiwan_billing->rollback();
                $Rslogin->rollback();
                // 可以记录日志或者输出错误信息
                return('失败'.$e->getMessage());
	            die();
            }
	    }elseif(sysconfig('game','gamelogin') == '2'){
	        try {
	            //其他登录器
                $d_taiwan = $sqlconnect;
                $d_taiwan->startTrans();
                $uid = $d_taiwan->table('accounts')->order('UID DESC')->value('UID') + 1;
                $d_taiwan->table('accounts')->insert(['UID'=>$uid,'accountname'=>$账号,'password'=>$密码,'qq'=>'']);
                $d_taiwan->table('limit_create_character')->insert(['m_id'=>$uid]);
                $d_taiwan->table('member_info')->insert(['m_id'=>$uid,'user_id'=>$uid]);
                $d_taiwan->table('member_join_info')->insert(['m_id'=>$uid]);
                $d_taiwan->table('member_miles')->insert(['m_id'=>$uid]);
                $d_taiwan->table('member_white_account')->insert(['m_id'=>$uid]);
                $d_taiwan->commit();
                $taiwan_login = Db::connect('taiwan_login');
                $taiwan_login->startTrans();
                $taiwan_login->table('member_login')->insert(['m_id'=>$uid]);
                $taiwan_login->commit();
                $taiwan_billing =  Db::connect('taiwan_billing');
                $taiwan_billing->startTrans();
                $taiwan_billing->table('cash_cera')->insert(['account'=>$uid,'cera'=>$赠点券]);
                $taiwan_billing->table('cash_cera_point')->insert(['account'=>$uid,'cera_point'=>$赠DB]);
                $taiwan_billing->commit();
                $taiwan_cain_2nd = Db::connect('taiwan_cain_2nd');
                $taiwan_cain_2nd->startTrans();
                $taiwan_cain_2nd->table('member_avatar_coin')->insert(['m_id'=>$uid]);
                $taiwan_cain_2nd->commit();
                $d_gmaster =Db::connect('d_gmaster');
                $d_gmaster->startTrans();
                $d_gmaster->table('login')->insert(['uid'=>$uid]);
                $d_gmaster->commit();
                return('ok');
	            die();
	        } catch (\Exception $e) {
                // 出现异常，回滚事务
                $d_taiwan->rollback();
                $taiwan_login->rollback();
                $taiwan_billing->rollback();
                $taiwan_cain_2nd->rollback();
                $d_gmaster->rollback();
                // 可以记录日志或者输出错误信息
                return('失败'.$e->getMessage());
	            die();
            }
	    }
	}
	
	public function reg(Request $request){
	    if($request->isAjax()){
			if($request->post('account') && $request->post('password') == $request->post('password2')) {
			} else {
				return $this->error('账号未输入或两次密码不一样');
				exit;
			}

			//验证码部分
			$session = $request->session();
			if(sysconfig('sms','smsstatus') == "1"){
			    if(md5($request->post('code')) != $session->post('regkey')){
    			    return $this->error('验证码不正确');
    				exit;
    			}
			}
			
			$data['name']=$request->post('account');
			$data['nickname']=$request->post('nickname');
			$data['ip'] = $ip = $request->getRemoteIp();
			$data['time'] = time();
            $data['tx'] = '/qstatic/image/headimg.jpg';
            
			if(Db::name('user')->where('name',$data['name'])->find()) {
				return $this->error('账号已被注册,请更换其他账号');
				exit;
			} elseif(Db::name('user')->where('nickname',$data['nickname'])->find()) {
				return $this->error('昵称已被占用,请更换其他昵称');
				exit;
			}

			//游戏互通部分
			if(sysconfig('game','gamelogin') != "0"){
			    $back = $this->zh_reg($data['name'],$request->post('password'),sysconfig('game','regdj'),sysconfig('game','regdb'));
			    if($back != 'ok'){
			        return $this->error($back);
			        die();
			    }
			}
            
			$data['pw']=md5($request->post('password'));
			
			//生成邀请码
			function getUniqueCdk($length = 8) {
                $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $randomString = '';
            
                do {
                    $randomString = '';
                    for ($i = 0; $i < $length; $i++) {
                        $randomString .= $characters[rand(0, strlen($characters) - 1)];
                    }
                } while (DB::name('user')->where('code', $randomString)->find());
            
                return $randomString;
            }
            
            $data['code']=getUniqueCdk(8);
            
            //如果开启验证码部分
            if(sysconfig('invite','istatus') == 1){
                if(!empty($request->post('yqcode'))){
                    $yquser = DB::name('user')->where('code', $request->post('yqcode'))->find();
                    if($yquser){
                        $data['inviteid'] = $yquser['id'];
                        DB::name('user')->where('id', $yquser['id'])->setInc('invitecs',1);
                    }
                }
                
            }
            
			
			$User=Db::name('user')->insertGetId($data);
            
			if($User) {
				return $this->success('注册成功请登陆');
				exit;
			}
    		
	    }else{
	       // $session = $request->session();
	       // $session->get('regkey');
	        return view('login/index/reg');
	    }
	    
	}
	
	public function sendcode(Request $request){
	    $code = rand(100000,999999);
	    $session = $request->session();
        $session->put(['regkey' => md5($code)]);
        $postUrl = 'https://uni.apistd.com/?action=sms.message.send&accessKeyId='.sysconfig('sms','Accesskey');
        // 要发送的 JSON 数据
        $data = array(
            'to' => $request->post('tel'),
            'signature' => sysconfig('sms','smssign'),
            'templateId' => 'pub_verif_basic',
            'templateData' => [
              'code' => $code
            ],
        );
        $jsonData = json_encode($data); 
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($ch);
        curl_close($ch);
        $back = json_decode($response,true);
        if($back['message'] == "Success"){
            return $this->success('发送成功');
        }else{
            return $this->error('错误:'.$back['message']);
        }
	}
	
	public function logout(){
	    $request = request();$session = $request->session();
	    $session->forget(['uid', 'name','key']);
	    $session = $request->session();
        $session->put(['redirect_url' => '/chat']);
	    return $this->error('已经退出登录',[],'/login/login');
	}

}
